package com.pro01.carcontrol.tcp;

import java.io.OutputStream;
import java.net.Socket;

public class TCPClient {
    private final String host;
    private final int port;
    private Socket socket;
    private OutputStream output;

    public TCPClient(String host, int port) {
        this.host = host;
        this.port = port;
        connect();
    }

    private void connect() {
        int retries = 3;
        while (retries-- > 0) {
            try {
                socket = new Socket(host, port);
                output = socket.getOutputStream();
                System.out.println("✅ 与小车建立连接");
                return;
            } catch (Exception e) {
                System.err.println("⚠️ 第 " + (3 - retries) + " 次连接失败：" + e.getMessage());
                try { Thread.sleep(1000); } catch (InterruptedException ignored) {}
            }
        }
        System.err.println("❌ 最终无法连接小车！");
    }

    public void sendCommand(String command) {
        try {
            if (socket == null || socket.isClosed()) {
                connect();
            }
            output.write(command.getBytes());
            output.flush();
            System.out.println("✅ 发送指令: " + command);
        } catch (Exception e) {
            System.err.println("❌ 发送失败: " + e.getMessage());
        }
    }

    public void close() {
        try {
            if (output != null) output.close();
            if (socket != null) socket.close();
            System.out.println("✅ 已关闭连接");
        } catch (Exception e) {
            System.err.println("❌ 关闭失败: " + e.getMessage());
        }
    }
}